package linkfinders;

import http.HTTPLoader;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class YTLinkFinder implements ILinkFinder
{

	@Override
	public ArrayList<? extends Link> getLinksFromUrl(String url)
	{

		return getLinksFromString(HTTPLoader.getTextFile(url), url);
	}

	@Override
	public ArrayList<? extends Link> getLinksFromString(String s, String url)
	{
		ArrayList<YTLink> links = new ArrayList<YTLink>();
		String regexp = "\"url=[^\"]*\"";
		Pattern p = Pattern.compile(regexp);
		Matcher m = p.matcher(s);
		if (m.find())
		{
			try
			{
				String temp = m.group();
				temp = temp.substring(temp.indexOf('"')+1, temp.lastIndexOf('"'));
				String[] videos = temp.split(",");
				for (int i = 0; i < videos.length; i++)
				{
					String[] tab = videos[i].split("\\\\u0026");
					String yturl = null;
					String type = null;
					String quality = null;
					for (int i1 = 0; i1 < tab.length; i1++)
					{
						String s1 = URLDecoder.decode(tab[i1],"UTF-8");
						if (s1.startsWith("url="))
							yturl = s1.substring(4);
						else if (s1.startsWith("type="))
							type = s1.substring(5).replace("%2F", "/");
						else if (s1.startsWith("quality="))
							quality = s1.substring(8);

					}
					links.add(new YTLink(yturl, type, quality));
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		return links;
	}

	@Override
	public ArrayList<? extends Link> getLinksDepthFromString(String s,
			String url, int depth)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ArrayList<? extends Link> getLinksDepthFromUrl(String url, int depth)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getFolder(String url)
	{
		// TODO Auto-generated method stub
		return null;
	}

}
